package dbExec

import (
	"database/sql"
	"reflect"
	"sync"
)

var mutex sync.Mutex

type AnalyzeEr interface {
	TableStruct(db *sql.DB) (any, error) //获取表结构
	TableIndex(db *sql.DB) (any, error)  //获取表索引信息
	TableDistributed()                   //获取表分布
	//SqlConditionCount()                //获取表行数
	GlobalVariables() //获取表变量
	GlobalStatus()    //获取表状态
}

type QuestionTypeEr interface {
	ImplicitConversion() //隐式转换
	FuzzyMatching()      //模糊匹配(非最左匹配)
}
type OptimizationEr interface {
	Explain()    //执行计划
	SqlRewrite() //sql 语句拆分
	Suggestion() //建议
}
type SqlParseEr interface {
	TableNameParse() (any, error)
	Parse() any
}
type SqlParseInput struct {
	Type string
	Sql  string `json:"sql"`
}
type AnalyzeInput struct {
	Type      string
	TableName string `json:"tableName"`
}
type OptimizationInput struct {
	Type string
}

func SqlParseInit(hs SqlParseInput) (t SqlParseEr) {
	mutex.Lock()
	defer mutex.Unlock()
	if v1, ok := dbTypeInterFuncRef[hs.Type]; ok {
		if v1.Kind() == reflect.Func {
			args := []reflect.Value{
				reflect.ValueOf(hs),
				reflect.ValueOf(sqlParseApi[hs.Type]),
			}
			i := v1.Call(args)
			for ii := 0; ii < len(i); ii++ {
				t = i[ii].Interface().(SqlParseEr)
			}
		}
	}
	return
}

func AnalyzeInit(hs AnalyzeInput) (t AnalyzeEr) {
	mutex.Lock()
	defer mutex.Unlock()
	if v1, ok := dbTypeInterFuncRef[hs.Type]; ok {
		if v1.Kind() == reflect.Func {
			args := []reflect.Value{
				reflect.ValueOf(hs),
				reflect.ValueOf(analyzeApi[hs.Type]),
			}
			i := v1.Call(args)
			for ii := 0; ii < len(i); ii++ {
				t = i[ii].Interface().(AnalyzeEr)
			}
		}
	}
	return
}

func OptimizationInit(hs OptimizationInput) (t OptimizationEr) {
	mutex.Lock()
	defer mutex.Unlock()
	if v1, ok := dbTypeInterFuncRef[hs.Type]; ok {
		if v1.Kind() == reflect.Func {
			args := []reflect.Value{
				reflect.ValueOf(hs),
				reflect.ValueOf(optimizationApi[hs.Type]),
			}
			i := v1.Call(args)
			for ii := 0; ii < len(i); ii++ {
				t = i[ii].Interface().(OptimizationEr)
			}
		}
	}
	return
}
